package org.az.netty_study.p13_自定义协议;


import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufAllocator;
import io.netty.channel.embedded.EmbeddedChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;

public class _1_自定义协议_ {
    public static void main(String[] args) throws Exception {
        EmbeddedChannel channel = new EmbeddedChannel(
                new LoggingHandler(),
                //帧解码器可以解决黏包半包问题，读取数据不完整就一直等，不向下handler传递，直到读取一条完整的数据
                new LengthFieldBasedFrameDecoder(1024, 16, 4, 0, 0),
                new CustomizeCodec()
        );
        CustomizeMessage message = new CustomizeMessage()
                .setType((byte) 1)
                .setMsg("hello world");
        //写一个出站消息
        channel.writeOutbound(message);
        //写一个入站消息
        ByteBuf buf = ByteBufAllocator.DEFAULT.buffer();
        new CustomizeCodec().encode(null, message, buf);
        //将buf切片，来模拟半包
        ByteBuf buf1 = buf.slice(0, 10);
        ByteBuf buf2 = buf.slice(10, buf.readableBytes() - 10);
        //writeInbound会release一次ByteBuf，所以需要先retain
        buf.retain();
        channel.writeInbound(buf1);
        channel.writeInbound(buf2);
    }
}
